#!/bin/bash
set -e

echo "Starting Todo App..."
echo "Current user: $(whoami)"
echo "Current directory: $(pwd)"
echo "Database directory permissions:"
ls -la /app/database/ || echo "Database directory does not exist"

# 确保数据库目录存在
if [ ! -d "/app/database" ]; then
    echo "Creating database directory..."
    mkdir -p /app/database
fi

echo "Database directory permissions after setup:"
ls -la /app/database/

# 确保数据库目录和文件有正确的权限
echo "Setting up database permissions..."
touch /app/database/agi-todo.db
chown nextjs:nodejs /app/database/agi-todo.db
chmod 644 /app/database/agi-todo.db
chown -R nextjs:nodejs /app/database
chmod -R 755 /app/database

# 初始化数据库
if [ ! -f /app/database/agi-todo.db ] || [ ! -s /app/database/agi-todo.db ]; then
    echo "Initializing database..."
    echo "DATABASE_URL: $DATABASE_URL"
    npx prisma migrate deploy
    echo "Database file after initialization:"
    ls -la /app/database/
else
    echo "Database already exists"
    ls -la /app/database/agi-todo.db
fi

# 启动应用
echo "Starting Node.js application..."
exec node server.js 